package com.karry.yl.service.baseinfo.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.karry.commons.base.impl.SuperServiceImpl;
import com.karry.yl.dao.baseinfo.EmployeeCertificateMapper;
import com.karry.yl.dao.baseinfo.EmployeeMapper;
import com.karry.yl.dao.personnel.TrainMapper;
import com.karry.yl.dao.system.UserMapper;
import com.karry.yl.domain.baseinfo.Employee;
import com.karry.yl.domain.baseinfo.EmployeeCertificate;
import com.karry.yl.domain.personnel.Train;
import com.karry.yl.domain.system.User;
import com.karry.yl.service.baseinfo.EmployeeService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.poi.ss.formula.ptg.NotEqualPtg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
public class EmployeeServiceImpl extends SuperServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private EmployeeCertificateMapper employeeCertificateMapper;
    @Autowired
    private TrainMapper trainMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void updateEmployeeData(String data, Long orgId) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> employeeMap = mapper.readValue(data, Map.class);
        Employee employee = saveEmployee(employeeMap, orgId);
        employee.setId(Long.parseLong((String) employeeMap.get("id")));
        employeeMapper.updateById(employee);
        Long id = employee.getId();
        employeeCertificateMapper.delete(new EntityWrapper<EmployeeCertificate>().eq("employeeId", id).eq("orgId", orgId));
        trainMapper.delete(new EntityWrapper<Train>().eq("employeeId", id).eq("orgId", orgId));
        List<EmployeeCertificate> employeeCertificateList = saveEmployeeCertificates(mapper, employeeMap, orgId, id);
        if (employeeCertificateList != null && employeeCertificateList.size() > 0) {
            for (EmployeeCertificate employeeCertificate : employeeCertificateList) {
                employeeCertificateMapper.insert(employeeCertificate);
            }
        }
        List<Train> trains = saveTrains(mapper, employeeMap, employee, orgId, id);
        if (trains != null && trains.size() > 0) {
            for (Train train : trains) {
                trainMapper.insert(train);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveEmployeeData(String data, Long orgId) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> employeeMap = mapper.readValue(data, Map.class);
        Employee employee = saveEmployee(employeeMap, orgId);
        employeeMapper.insert(employee);
        Long id = employee.getId();
        List<EmployeeCertificate> employeeCertificateList = saveEmployeeCertificates(mapper, employeeMap, orgId, id);
        if (employeeCertificateList != null && employeeCertificateList.size() > 0) {
            for (EmployeeCertificate employeeCertificate : employeeCertificateList) {
                employeeCertificateMapper.insert(employeeCertificate);
            }
        }
        List<Train> trains = saveTrains(mapper, employeeMap, employee, orgId, id);
        if (trains != null && trains.size() > 0) {
            for (Train train : trains) {
                trainMapper.insert(train);
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveUser(String data, Long orgId) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> dataMap = mapper.readValue(data, Map.class);
        User user = new User();
        user.setOrgId(orgId);
        //如果密码是空的是不修改密码
        if(!StringUtils.isEmpty((String) dataMap.get("password"))){
            user.setPassword(DigestUtils.md5Hex((String)dataMap.get("password")));
        }
        user.setPrimary(false);
        user.setPhone((String) dataMap.get("phone"));
        user.setUserCode((String) dataMap.get("userCode"));
        user.setStatus(Integer.parseInt(((String) dataMap.get("status")) == null ? "0" : "1"));
        user.setRoleId(Long.parseLong((String) dataMap.get("roleId")));
        user.setUserName((String) dataMap.get("userName"));
        if (StringUtils.isEmpty((String) dataMap.get("userId"))) {
          //第一次设置
            userMapper.insert(user);
            Employee employee = new Employee();
            employee.setId(Long.parseLong((String) dataMap.get("employeeId")));
            employee.setUserId(user.getId());
            employeeMapper.updateById(employee);
        }else {
            //修改操作
            user.setId(Long.parseLong((String) dataMap.get("userId")));
            userMapper.updateById(user);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void leaveOffice(Long id) {
        Employee employee = employeeMapper.selectById(id);
        //设置离职
        employee.setStatus(2);
        employee.setDeleted(1);
        Long userId = employee.getUserId();
        if(!StringUtils.isEmpty(userId)){
            userMapper.deleteById(userId);
        }
        employee.setUserId(-1L);
        employeeMapper.updateById(employee);
    }

    private Employee saveEmployee(Map<String, Object> employeeMap, Long orgId) throws Exception {
        Employee employee = new Employee();
        employee.setAvatar("");
        if (!StringUtils.isEmpty((String) employeeMap.get("avatar"))) {
            employee.setAvatar((String) employeeMap.get("avatar"));
        }
        employee.setName("");
        if (!StringUtils.isEmpty((String) employeeMap.get("name"))) {
            employee.setName((String) employeeMap.get("name"));
        }
        employee.setIdNo("");
        if (!StringUtils.isEmpty((String) employeeMap.get("idNo"))) {
            employee.setIdNo((String) employeeMap.get("idNo"));
        }
        if (!StringUtils.isEmpty((String) employeeMap.get("gender"))) {
            employee.setGender(Integer.parseInt((String) employeeMap.get("gender")));
        }
        employee.setNation("");
        if (!StringUtils.isEmpty((String) employeeMap.get("nation"))) {
            employee.setNation((String) employeeMap.get("nation"));
        }
        if (!StringUtils.isEmpty((String) employeeMap.get("maritalStatus"))) {
            employee.setMaritalStatus(Integer.parseInt((String) employeeMap.get("maritalStatus")));
        }
        if (!StringUtils.isEmpty((String) employeeMap.get("politicsStatus"))) {
            employee.setPoliticsStatus(Integer.parseInt((String) employeeMap.get("politicsStatus")));
        }
        if (!StringUtils.isEmpty((String) employeeMap.get("culture"))) {
            employee.setCulture(Integer.parseInt((String) employeeMap.get("culture")));
        }
        employee.setContactPhone("");
        if (!StringUtils.isEmpty((String) employeeMap.get("contactPhone"))) {
            employee.setContactPhone((String) employeeMap.get("contactPhone"));
        }
        employee.setUrgencyContactPhone("");
        if (!StringUtils.isEmpty((String) employeeMap.get("urgencyContactPhone"))) {
            employee.setUrgencyContactPhone((String) employeeMap.get("urgencyContactPhone"));
        }
        employee.setTemporaryAddress("");
        if (!StringUtils.isEmpty((String) employeeMap.get("temporaryAddress"))) {
            employee.setTemporaryAddress((String) employeeMap.get("temporaryAddress"));
        }

        employee.setHomeAddress("");
        if (!StringUtils.isEmpty((String) employeeMap.get("homeAddress"))) {
            employee.setHomeAddress((String) employeeMap.get("homeAddress"));
        }

        if (!StringUtils.isEmpty((String) employeeMap.get("departmentId"))) {
            employee.setDepartmentId(Long.parseLong((String) employeeMap.get("departmentId")));
        }
        employee.setDepartmentName("");
        if (!StringUtils.isEmpty((String) employeeMap.get("departmentName"))) {
            employee.setDepartmentName((String) employeeMap.get("departmentName"));
        }

        if (!StringUtils.isEmpty((String) employeeMap.get("type"))) {
            employee.setType(Long.parseLong((String) employeeMap.get("type")));
        }
        employee.setPostName("");
        if (!StringUtils.isEmpty((String) employeeMap.get("postName"))) {
            employee.setPostName((String) employeeMap.get("postName"));
        }
        if (!StringUtils.isEmpty((String) employeeMap.get("jobTitle"))) {
            employee.setJobTitle(Integer.parseInt((String) employeeMap.get("jobTitle")));
        }

        if (!StringUtils.isEmpty((String) employeeMap.get("identityCardJust"))) {
            employee.setIdentityCardJust((String) employeeMap.get("identityCardJust"));
        }

        if (!StringUtils.isEmpty((String) employeeMap.get("identityCardAgainst"))) {
            employee.setIdentityCardAgainst((String) employeeMap.get("identityCardAgainst"));
        }

        employee.setLaborContract("");
        if (!StringUtils.isEmpty((String) employeeMap.get("laborContracts"))) {
            employee.setLaborContract((String) employeeMap.get("laborContracts"));
        }
        if (!StringUtils.isEmpty((String) employeeMap.get("birthday"))) {
            String birthday = (String) employeeMap.get("birthday");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date parseData = simpleDateFormat.parse(birthday);
            employee.setBirthday(parseData);
        }
        employee.setOrgId(orgId);
        employee.setStatus(1);
        return employee;
    }

    private List<Train> saveTrains(ObjectMapper mapper, Map<String, Object> employeeMap, Employee employee, Long orgId, Long id) throws IOException {
        List<Train> trains = new ArrayList<>();
        if (!StringUtils.isEmpty((String) employeeMap.get("trainList"))) {
            String trainList = (String) employeeMap.get("trainList");
            if (trainList.contains("/")) {
                trainList = trainList.replaceAll("/", "");
            }
            String[] strs = trainList.split("and");
            for (String str : strs) {
                Train train = mapper.readValue(str, Train.class);
                train.setOrgId(orgId);
                train.setEmployeeId(id);
                train.setEmployeeName(employee.getName());
                trains.add(train);
            }

        }
        return trains;
    }

    private List<EmployeeCertificate> saveEmployeeCertificates(ObjectMapper mapper, Map<String, Object> employeeMap, Long orgId, Long id) throws IOException {
        List<EmployeeCertificate> employeeCertificates = new ArrayList<>();
        if (!StringUtils.isEmpty((String) employeeMap.get("employeeCertificateList"))) {
            String employeeCertificateList = (String) employeeMap.get("employeeCertificateList");
            if (employeeCertificateList.contains("/")) {
                employeeCertificateList = employeeCertificateList.replaceAll("/", "");
            }
            String[] employeeCertificateStrs = employeeCertificateList.split("and");
            for (String str : employeeCertificateStrs) {
                EmployeeCertificate employeeCertificate = mapper.readValue(str, EmployeeCertificate.class);
                employeeCertificate.setOrgId(orgId);
                employeeCertificate.setEmployeeId(id);
                employeeCertificates.add(employeeCertificate);
            }
        }
        return employeeCertificates;
    }



}
